import useThemeStore from '@/store/theme'

// 拍平路由
export const flattenTree = (data) => {
  const flatList = []

  function traverse (node) {
    flatList.push(node) // 添加当前节点到结果列表中
    if (node.children && node.children.length) { // 如果存在子节点，则继续遍历子节点
      node.children.forEach(child => traverse(child))
    }
  }

  data.forEach(rootNode => traverse(rootNode)) // 对每个根节点进行遍历

  return flatList
}

// 拍平路由为 router.currentRoute.value.matchedTitle 模式
export const findPath = (path, arr) => {
  for (const item of arr) {
    const data = [item]
    if (item.menuPath.toLowerCase() === path) {
      return data
    }

    if (item.children && item.children.length) {
      const value = findPath(path, item.children)

      if (value.length) {
        data.push(...value)
        return data
      }
    }
  }
  return []
}

// 变量前缀
const pre = '--el-color-primary'
// 白色混合色
const mixWhite = '#ffffff'
const mixBlack = '#000000'

// 获取节点
const node = document.documentElement
// 设置主题色
export const themeChange = (data) => {
  if (!data) {
    node.style.cssText = ''
    return
  }
  const themeStore = useThemeStore()

  node.style.setProperty(pre, data)

  node.style.setProperty('--el-color-primary-dark-2', mix(data, themeStore.scheme ? mixWhite : mixBlack, 0.1))

  for (let i = 1; i < 10; i += 1) {
    node.style.setProperty(`${pre}-light-${i}`, mix(data, themeStore.scheme ? mixBlack : mixWhite, i * 0.1))
  }
  console.log(node.style.cssText)
}

const mix = (color1, color2, weight) => {
  weight = Math.max(Math.min(Number(weight), 1), 0)
  const r1 = parseInt(color1.substring(1, 3), 16)
  const g1 = parseInt(color1.substring(3, 5), 16)
  const b1 = parseInt(color1.substring(5, 7), 16)
  const r2 = parseInt(color2.substring(1, 3), 16)
  const g2 = parseInt(color2.substring(3, 5), 16)
  const b2 = parseInt(color2.substring(5, 7), 16)
  let r = Math.round(r1 * (1 - weight) + r2 * weight)
  let g = Math.round(g1 * (1 - weight) + g2 * weight)
  let b = Math.round(b1 * (1 - weight) + b2 * weight)
  r = ('0' + (r || 0).toString(16)).slice(-2)
  g = ('0' + (g || 0).toString(16)).slice(-2)
  b = ('0' + (b || 0).toString(16)).slice(-2)
  return '#' + r + g + b
}

// 设置图标
export const faviconChange = (data) => {
  if (!data) return
  let favicon = document.querySelector('link[rel="icon"]')
  // If a <link rel="icon"> element already exists,
  // change its href to the given link.
  if (favicon !== null) {
    favicon.href = data
    // Otherwise, create a new element and append it to <head>.
  } else {
    favicon = document.createElement('link')
    favicon.rel = 'icon'
    favicon.href = data
    document.head.appendChild(favicon)
  }
}

/**
 * 合并两个对象, other过滤空值
 * @param {Object} object
 * @param {Object} other
 */
export const mergeObj = (object, other) => {
  Object.keys(other).forEach((key) => {
    if (other[key] === null || other[key] === '') {
      delete other[key]
    }
  })
  return { ...object, ...other }
}
